/* Copyright (c) 2016-2020 Enfry Ltd. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Enfry. 
 * You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with Enfry.
 */
package com.enfry.storage.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;
import com.enfry.validation.IValidateService;
import com.enfry.storage.Response;
import com.enfry.storage.common.Constants;
import com.enfry.storage.exception.ExCode;
import com.enfry.storage.interceptor.ValidateInterceptor;

/**
 * 验证拦截器
 * @Title com.enfry.storage.interceptor.ValidateInterceptor
 * @author liulei
 * @date 2016年7月25日
 */
public class ValidateInterceptor extends HandlerInterceptorAdapter {
    private static Logger logger = LoggerFactory.getLogger(ValidateInterceptor.class);

    @Resource
    protected IValidateService validateService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getServletPath().replaceFirst("/", "");
        logger.debug("参数验证，path：" + path);
        // 根据path获取校验规则来校验请求的入口数据，
        Map<String, String> validateResults = validateService.validate(this.getParamMap(request), path);
        if (validateResults != null && validateResults.size() > 0) {
            Response rep = new Response(ExCode.PARAM_ERR.getCode(), ExCode.PARAM_ERR.getMsg() + "，" + validateResults.values().toString());
            response.getWriter().write(JSONObject.toJSONString(rep));
            return false;
        }
        return true;
    }

    @SuppressWarnings("unchecked")
    public Map<String, String> getParamMap(HttpServletRequest request) {
        Map<String, String> paramMap = new HashMap<>();
        Map<String, String[]> requestMap = request.getParameterMap();
        if(request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile multipartFile = multipartRequest.getFile(Constants.FILE_PARAM_NAME);
            if(multipartFile != null) {
                paramMap.put(Constants.FILE_PARAM_NAME+"_size", Long.toString(multipartFile.getSize()));
            }
        }
        for (Map.Entry<String, String[]> entry : requestMap.entrySet()) {
            paramMap.put(entry.getKey(), entry.getValue()[0]);
        }
        return paramMap;
    }
}
